from math import log
from re import T
import requests
import string
import random
import json
import aes 
import hashlib
import urllib.request
import http.cookiejar as cookielib
try:
    import thread
except ImportError:
    import _thread as thread
import time

matching_list = {}
team_list = {}
userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
mafengwoSession = requests.session()
mafengwoSession.cookies = cookielib.LWPCookieJar(filename = "mafengwoCookies.txt")
login_token = ''
token = ''

game_ids = {257289795134339:'DATA2'}

##登录网站
def login():
    username = 'xp168'
    password = 'Lxp74352090'
    password = hashlib.md5(password.encode(encoding='UTF-8')).hexdigest()
    url = 'https://www.xbb13oq.com:6001/api/site/group/account/memberLogin/v3/login'
    postData = {"name":username,"password":password,"version":1,"kaptchcate":99,"isLogin":True,"flag":1}
    hrhkp = nonce()
    tulsy = str(int(time.time()))
    header ={
        "User-Agent": userAgent,
        "HRHKP": hrhkp,
        "TULSY": tulsy,
        "DSRVY": "n7XaKqa1O2k22Q5HyYb8ggf6h6JWlPmD",
        "CTBDQ": "0FpLbdwfQ0",
        "NLGFN": uuid(),
        "XGHBQ": hexData(postData,hrhkp,tulsy),
        "fuqva":"v1.0.1",
        "qjzdv":"2",
        "referer":"https://www.xbb13oq.com:6001/app/home",
        "skktw":"web",
        "content-type": "application/json",
        }
    enc = aes.encrypt(json.dumps(postData,separators=(',',':')))
    post = json.dumps({"xx":enc})
    r = mafengwoSession.post(url, data = post, headers = header)
    if r.status_code == 200:
        res = json.loads(r.text)
        res = aes.decrypt(res['x1'])
        print(res)
        res = json.loads(res)
        mafengwoSession.cookies.save()
        login_token = res['data']['token']
        with open("login_token.txt", "w") as f:
            f.write(login_token)


def nonce():
    ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 16))
    return ran_str
def hexData(t, e, i):
    t =json.dumps(t,separators=(',',':')) 
    hex =t + "|" + e + "|" + i + "|" + aes.keyWord
    
    return hashlib.sha1(hex.encode("utf-8")).hexdigest()
def uuid():
    return 'B20CA4D8-E77D-4118-9855-462388FBA836'
###判断是否登录
def isLoginStatus():
    # 通过访问个人中心页面的返回状态码来判断是否为登录状态
    routeUrl = "https://www.xbb13oq.com:6001/app/home"
    header = {
        "User-Agent": userAgent,
    }
    # 下面有两个关键点
        # 第一个是header，如果不设置，会返回500的错误
        # 第二个是allow_redirects，如果不设置，session访问时，服务器返回302，
        # 然后session会自动重定向到登录页面，获取到登录页面之后，变成200的状态码
        # allow_redirects = False  就是不允许重定向
    responseRes = mafengwoSession.get(routeUrl, headers = header, allow_redirects = False)
    print(f"isLoginStatus = {responseRes.status_code}")
    if responseRes.status_code != 200:
        return False
    else:
        return True
def getToken():
    mafengwoSession.cookies.load()
    url = 'https://www.xbb13oq.com:6001/api/site/game/venueLaunch/v1/launch'
    postData = {"isApp":False,"https":True,"isManualLaunch":False,"clientType":"web","venueEnName":"YBDJ","gameCode":""}
    hrhkp = nonce()
    tulsy = str(int(time.time()))
    f = open('login_token.txt', 'r')
    login_token = f.read()
    header ={
        "User-Agent": userAgent,
        "HRHKP": hrhkp,
        "TULSY": tulsy,
        "DSRVY": "n7XaKqa1O2k22Q5HyYb8ggf6h6JWlPmD",
        "CTBDQ": "0FpLbdwfQ0",
        "NLGFN": uuid(),
        "XGHBQ": hexData(postData,hrhkp,tulsy),
        "fuqva":"v1.0.1",
        "qjzdv":"2",
        "referer":"https://www.xbb13oq.com:6001/app/home",
        "skktw":"web",
        "content-type": "application/json",
        "rwnav": login_token,
        }
    enc = aes.encrypt(json.dumps(postData,separators=(',',':')))
    post = json.dumps({"xx":enc})
    r = mafengwoSession.post(url, data = post, headers = header)
    if r.status_code == 200:
        res = json.loads(r.text)
        # print(res['x1'])
        res = aes.decrypt(res['x1'])
        # print(res)
        res = json.loads(res)
        # print(res)

        if res['code'] == 10103:
            login()
            getToken()
        parsed=urllib.parse.urlparse(res['data']['url'])
        querys = urllib.parse.parse_qs(parsed.query)
        token=querys['token'][0]
        print(token)
        with open("token.txt", "w") as f:
            f.write(token)



def getMatch():
    url = 'https://jiadianw.koosieji.com/game/index?game_id=0&flag=3'
    f = open('token.txt', 'r')
    token = f.read()
    headers = {
        'token': token
    }
    r = requests.get(url,headers=headers)
    # if r.status_code == 401:
    #     login()
    if r.status_code == 200:
        print(type(r.text))

        res = json.loads(r.text)

        list = res['data']
        for match in list:
            match = eval(match)
            match_id = match['id']
            if match['is_live'] == 2 and match['game_id'] in game_ids.keys:
                matching_list[match_id] = {
                    'game_name': game_ids[match['game_id']],
                    'match_name': match['match_cn_team'],
                    'team': {},
                    'odds': {}
                }
                away = match['away']
                home = match['home']
                matching_list[match_id]['team'].update({
                    2: {
                        'team_name': away['team_name'],
                        'team_id': away['team_id'],
                    },
                    1: {
                        'team_name': home['team_name'],
                        'team_id':  home['team_id'],
                    }
                })
# login()


# getToken()
getMatch()


# getMatch('https://api-v4.jai78lusk.com/api/v4/events/paginate?combo=false&outright=false&timing=inplay&sort_by_popular=false&market_option=MATCH&lang=zh&timezone=Asia/Shanghai')
# with open("fthy.txt", "w") as f:
#     f.write(json.dumps(matching_list, sort_keys=True, indent=2))
